#! /usr/bin/env python
# -*- coding: utf-8 -*-

# *************************************************************
#  Copyright (c) Huoty - All rights reserved
#
#      Author: Huoty <sudohuoty@gmail.com>
#  CreateTime: 2016-10-15 15:42:37
# *************************************************************

"""通用模块"""

import math
import json
import string
import random
import datetime
from functools import partial


def json_serial_fallback(obj):
    """JSON serializer for objects not serializable by default json code"""
    if isinstance(obj, (datetime.datetime, datetime.date)):
        return str(obj)
    if isinstance(obj, bytes):
        return obj.decode("utf-8")
    raise TypeError ("%s is not JSON serializable" % obj)

json_dumps = partial(json.dumps, default=json_serial_fallback)

def random_str(length):
    chars = (string.ascii_letters + string.digits) * int(math.ceil(length / 62))
    return "".join(random.sample(chars, length))

def random_lower_str(length):
    chars = (string.ascii_lowercase + string.digits) * int(math.ceil(length / 36))
    return "".join(random.sample(chars, length))

def random_hex_str(length):
    chars = list("abcdef1234567890" * int(math.ceil(length / 16)))
    random.shuffle(chars)
    return "".join(chars[:length])

def genkey(length):
    chars = "wertuoasdfhklzxcvbnm1234567890" * int(math.ceil(length / 30))
    return "".join(random.sample(chars, length))


class Colorizing(object):
    colors = {
        'none': "",
        'default': "\033[0m",
        'bold': "\033[1m",
        'underline': "\033[4m",
        'blink': "\033[5m",
        'reverse': "\033[7m",
        'concealed': "\033[8m",

        'black': "\033[30m",
        'red': "\033[31m",
        'green': "\033[32m",
        'yellow': "\033[33m",
        'blue': "\033[34m",
        'magenta': "\033[35m",
        'cyan': "\033[36m",
        'white': "\033[37m",

        'on_black': "\033[40m",
        'on_red': "\033[41m",
        'on_green': "\033[42m",
        'on_yellow': "\033[43m",
        'on_blue': "\033[44m",
        'on_magenta': "\033[45m",
        'on_cyan': "\033[46m",
        'on_white': "\033[47m",

        'beep': "\007",
    }

    def __call__(self, s, color='none'):
        if color in self.colors:
            return "{0}{1}{2}".format(
                self.colors[color],
                s,
                self.colors['default'])
        else:
            return s


# Script starts from here

if __name__ == "__main__":
    pass
